/*
 * 地区选择组件
 * options.el 组件容器Id
 * options.level 地区层级（1-4）
 * options.initUrl 初始化数据
 * options.nextUrl 选择地区获取下级数据
 */
define(function(require,exports,module){
    var Backbone = require('backbone');
    var _ = require('_');

    var AreaModel = Backbone.Model.extend();
    var AreaView = Backbone.View.extend({
        tagName:"select",
        initialize:function(options){
            this.template = options.template;
            var _this =this;
            _.bindAll(this, "render");
            this.model.fetch({success: _this.render});
        },
        render:function(){
            var data = this.model.toJSON();
            if(data.areas === null || (data.areas && data.areas.length<=0) ){this.remove(); return false; }
            this.$el.html(this.template(data));
            this.$el.removeClass("fn-hide");
        }
    });
    var AppView = Backbone.View.extend({
        events:{
            "change .area-prov" : "changeProv",
            "change .area-city" : "changeCity",
            "change .area-dist" : "changeDist",
            "change .area-town" : "changeTown"
        },
        initialize:function(options){
            var _this = this,initArea = this.$(".area-area").val();
            //初始化参数
            this.level = options.level ? options.level : 3;//选择层级（1-4）
            this.initUrl = options.initUrl;
            this.nextUrl = options.nextUrl;
            this.area = this.$(".area-area");//已选地区id隐藏域

            //初始化已选地区
            var defaultArea = $.trim(this.area.val());//默认已选区域
            this.model = new AreaModel();
            this.model.url =defaultArea=="" ? this.initUrl : this.initUrl+'&areaid=' + defaultArea;
            _.bindAll(this, "render");
            this.model.fetch({ success: _this.render });
        },
        render:function(){
            var data = this.model.toJSON();
            var _this = this;
            function initialArea(addClass,template){
                var aView = new AreaView({
                    model:_this.model,
                    className:"area-"+addClass,
                    template : _.template(template)
                });
                _this.$el.append(aView.el);
            }
            initialArea("prov","<option value=''>请选择省份</option><% _.each(prov, function(p){ %><option <% if(p.selected){ %>selected='selected'<% } %> value='<%= p.id %>'><%= p.name %></option><% }); %>");
            if(_this.level>1 && data.city){
                initialArea("city","<option value=''>请选择城市</option><% _.each(city, function(c){ %><option <% if(c.selected){ %>selected='selected'<% } %> value='<%= c.id %>'><%= c.name %></option><% }); %>");
            }else{ return; }
            if(_this.level>2 && data.district){
                initialArea("dist","<option value=''>请选择县区</option><% _.each(district, function(d){ %><option <% if(d.selected){ %>selected='selected'<% } %> value='<%= d.id %>'><%= d.name %></option><% }); %>");
            }else{ return; }
            if(_this.level>3 && data.town ){
                initialArea("town","<option value=''>请选择乡镇</option><% _.each(town, function(t){ %><option <% if(t.selected){ %>selected='selected'<% } %> value='<%= t.id %>'><%= t.name %></option><% }); %>");
            }else{ return; }
        },
        changeProv : function(event){
            //改变省份
            this.changeArea(event,1);
        },
        changeCity : function(event){
            //改变城市
            this.changeArea(event,2);
        },
        changeDist : function(event){
            //改变县区
            this.changeArea(event,3);
        },
        changeTown:function(event){
            this.area.val($(event.target).val());
        },
        changeArea:function(event,level){
            //改变区域操作
            var requireLevel,changeClass,createClass,createName,changeId;
            switch(level){
                case 1:
                    requireLevel = 1;
                    changeClass = "prov";
                    createClass = "city";
                    createName="城市";
                    break;
                case 2 :
                    requireLevel = 2;
                    changeClass = "city";
                    createClass = "dist";
                    createName="县区";
                    break;
                case 3 :
                    requireLevel = 3;
                    changeClass = "dist";
                    createClass = "town";
                    createName="乡镇";
                    break;
            }

            this.$(".area-"+changeClass).nextAll().remove();
            changeId = this.$(".area-"+changeClass).val();
            if(changeId && this.level > requireLevel){
                var requireModel = new AreaModel();
                requireModel.url = this.nextUrl+"&parentid="+$(event.target).val();
                var requireView = new AreaView({
                    model:requireModel,
                    className:"fn-hide area-"+createClass,
                    template : _.template("<option value=''>请选择"+createName+"</option><% _.each(areas, function(area){ %><option <% if(area.selected){ %>selected='selected'<% } %> value='<%= area.id %>'><%= area.name %></option><% }); %>")
                });
                this.$el.append(requireView.el);
            }
            this.area.val($(event.target).val());
        }
    });
    module.exports = AppView;
});